<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="12">
            <a-form-item label="订单编号">
              <a-input placeholder="请输入订单编号" v-model="queryParam.orderNo" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="12">
            <a-form-item label="客户名称">
              <a-input placeholder="请输入客户名称" v-model="queryParam.customerName" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="12">
            <a-form-item label="工程名称">
              <a-input placeholder="请输入工程名称" v-model="queryParam.projectName" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="12">
            <a-form-item label="订单状态">
              <j-dict-select-tag
                v-model="queryParam.status"
                placeholder="请选择订单状态"
                dictCode="order_status"
                allowClear
              />
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :md="6" :sm="12">
              <a-form-item label="下单时间">
                <j-date
                  v-model="queryParam.orderDate"
                  :show-time="true"
                  date-format="YYYY-MM-DD"
                  placeholder="请选择下单时间"
                  style="width: 100%"
                ></j-date>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="12">
              <a-form-item label="交付日期">
                <j-date
                  v-model="queryParam.deliveryDate"
                  date-format="YYYY-MM-DD"
                  placeholder="请选择交付日期"
                  style="width: 100%"
                ></j-date>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="12">
              <a-form-item label="销售负责人">
                <j-select-employee-modal
                  v-model="queryParam.salesPersonId"
                  :multiple="false"
                  :departName="'销售部'"
                  placeholder="请选择销售负责人"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="12">
              <a-form-item label="客户省份">
                <a-input placeholder="请输入客户省份" v-model="queryParam.customerProvince" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="12">
              <a-form-item label="客户城市">
                <a-input placeholder="请输入客户城市" v-model="queryParam.customerCity" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="12">
              <a-form-item label="客户区县">
                <a-input placeholder="请输入客户区县" v-model="queryParam.customerDistrict" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="12">
              <a-form-item label="工程省份">
                <a-input placeholder="请输入工程省份" v-model="queryParam.projectProvince" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="12">
              <a-form-item label="工程城市">
                <a-input placeholder="请输入工程城市" v-model="queryParam.projectCity" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="12">
              <a-form-item label="工程区县">
                <a-input placeholder="请输入工程区县" v-model="queryParam.projectDistrict" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="12">
              <a-form-item label="产品系列">
                <a-input placeholder="请输入产品系列" v-model="queryParam.productSeries" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="销售额范围">
                <a-input-group compact>
                  <a-input-number style="width: 45%" placeholder="最小值" v-model="queryParam.minTotalAmount" />
                  <a-input
                    style="width: 10%; border-left: 0; border-right: 0; pointer-events: none; backgroundcolor: #fff"
                    placeholder="~"
                    disabled
                  />
                  <a-input-number style="width: 45%" placeholder="最大值" v-model="queryParam.maxTotalAmount" />
                </a-input-group>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="成本范围">
                <a-input-group compact>
                  <a-input-number style="width: 45%" placeholder="最小值" v-model="queryParam.minTotalCost" />
                  <a-input
                    style="width: 10%; border-left: 0; border-right: 0; pointer-events: none; backgroundcolor: #fff"
                    placeholder="~"
                    disabled
                  />
                  <a-input-number style="width: 45%" placeholder="最大值" v-model="queryParam.maxTotalCost" />
                </a-input-group>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="利润范围">
                <a-input-group compact>
                  <a-input-number style="width: 45%" placeholder="最小值" v-model="queryParam.minProfit" />
                  <a-input
                    style="width: 10%; border-left: 0; border-right: 0; pointer-events: none; backgroundcolor: #fff"
                    placeholder="~"
                    disabled
                  />
                  <a-input-number style="width: 45%" placeholder="最大值" v-model="queryParam.maxProfit" />
                </a-input-group>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="6" :sm="8">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 订单汇总信息卡片 -->
    <a-card :bordered="false" class="order-summary-card" style="margin-bottom: 16px">
      <div class="summary-header">
        <div class="summary-title"><a-icon type="bar-chart" /> 订单汇总信息</div>
        <div class="summary-filter">
          <a-radio-group v-model="summaryTimeRange" @change="handleSummaryTimeRangeChange" button-style="solid">
            <a-radio-button value="today">当日</a-radio-button>
            <a-radio-button value="week">近七天</a-radio-button>
            <a-radio-button value="month">近一个月</a-radio-button>
          </a-radio-group>
        </div>
      </div>
      <div class="summary-content">
        <a-row :gutter="16">
          <a-col :span="6">
            <div class="summary-card summary-card-blue">
              <div class="summary-icon">
                <a-icon type="shopping-cart" />
              </div>
              <div class="summary-data">
                <div class="summary-label">订单总数</div>
                <div class="summary-value">
                  <count-to :start-val="0" :end-val="summaryData.totalOrders || 0" :duration="2000" />
                  <span class="summary-unit">笔</span>
                </div>
              </div>
            </div>
          </a-col>
          <a-col :span="6">
            <div class="summary-card summary-card-green">
              <div class="summary-icon">
                <a-icon type="account-book" />
              </div>
              <div class="summary-data">
                <div class="summary-label">总销售额</div>
                <div class="summary-value">
                  <span class="summary-prefix">¥</span>
                  <count-to :start-val="0" :end-val="summaryData.totalAmount || 0" :duration="2000" :decimals="2" />
                </div>
              </div>
            </div>
          </a-col>
          <a-col :span="6">
            <div class="summary-card summary-card-orange">
              <div class="summary-icon">
                <a-icon type="wallet" />
              </div>
              <div class="summary-data">
                <div class="summary-label">总成本</div>
                <div class="summary-value">
                  <span class="summary-prefix">¥</span>
                  <count-to :start-val="0" :end-val="summaryData.totalCost || 0" :duration="2000" :decimals="2" />
                </div>
              </div>
            </div>
          </a-col>
          <a-col :span="6">
            <div class="summary-card summary-card-red">
              <div class="summary-icon">
                <a-icon type="rise" />
              </div>
              <div class="summary-data">
                <div class="summary-label">总利润</div>
                <div class="summary-value">
                  <span class="summary-prefix">¥</span>
                  <count-to :start-val="0" :end-val="summaryData.totalProfit || 0" :duration="2000" :decimals="2" />
                  <div class="profit-rate">
                    利润率:
                    <count-to :start-val="0" :end-val="summaryData.profitRate || 0" :duration="2000" :decimals="2" />%
                  </div>
                </div>
              </div>
            </div>
          </a-col>
        </a-row>
      </div>
    </a-card>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增订单</a-button>
      <a-button type="primary" icon="download" @click="handleExport">导出</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel">
            <a-icon type="delete" />
            批量删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down" />
        </a-button>
      </a-dropdown>
      <!-- 优化软件类型切换按钮 -->
      <a-button type="primary" icon="swap" @click="handleSwitchOptimizeSoftType" style="margin-left: 8px">
        切换优化软件类型 (当前: {{ currentOptimizeSoftTypeText }})
      </a-button>
      <!-- 门窗类型切换按钮 - 仅在新格尔优化软件时显示 -->
      <a-button
        v-if="currentOptimizeSoftType === 1"
        type="default"
        icon="build"
        @click="handleSwitchWindowDoorType"
        style="margin-left: 8px"
      >
        切换门窗类型 (当前: {{ currentWindowDoorTypeText }})
      </a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px" v-if="selectedRowKeys.length > 0">
        <i class="anticon anticon-info-circle ant-alert-icon"></i>已选择&nbsp;<a style="font-weight: 600">{{
          selectedRowKeys.length
        }}</a
        >项&nbsp;&nbsp;
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        bordered
        size="middle"
        rowKey="id"
        :key="tableKey"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :scroll="{ x: 'max-content' }"
        class="j-table-force-nowrap white-bg-table"
        @change="handleTableChange"
      >
        <!-- 订单状态 -->
        <template slot="statusSlot" slot-scope="text, record">
          <span v-if="record.status_dictText">{{ record.status_dictText }}</span>
          <j-dict-tag v-else :value="text" dictCode="order_status" />
        </template>

        <!-- 金额格式化 -->
        <template slot="moneySlot" slot-scope="text">
          <span v-if="text !== undefined && text !== null">{{
            Number(text).toLocaleString('zh-CN', { style: 'currency', currency: 'CNY', minimumFractionDigits: 2 })
          }}</span>
          <span v-else>¥0.00</span>
        </template>

        <!-- 客户地址 -->
        <template slot="customerAddressSlot" slot-scope="text, record">
          <span>{{
            [record.customerProvince, record.customerCity, record.customerDistrict].filter(Boolean).join(' ')
          }}</span>
        </template>

        <!-- 工程地址 -->
        <template slot="projectAddressSlot" slot-scope="text, record">
          <span>{{
            [record.projectProvince, record.projectCity, record.projectDistrict].filter(Boolean).join(' ')
          }}</span>
        </template>

        <!-- 操作按钮 -->
        <template slot="actionSlot" slot-scope="text, record">
          <!-- 添加审核按钮，仅当订单状态为0（待审核）时显示 -->
          <template v-if="record.status === 0 || record.status === '0'">
            <a @click="handleAudit(record)">审核</a>
            <a-divider type="vertical" />
          </template>
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleDetail(record)">详情</a>
          <a-divider type="vertical" />
          <a @click="() => handleDelete(record.id)">删除</a>
        </template>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <product-order-modal ref="modalForm" @ok="modalFormOk"></product-order-modal>

    <!-- 审核模态框 -->
    <a-modal
      title="订单审核"
      :visible="auditModalVisible"
      :confirmLoading="auditLoading"
      @ok="submitAudit"
      @cancel="cancelAudit"
      width="600px"
    >
      <a-spin :spinning="auditLoading">
        <a-form :form="auditForm" layout="vertical">
          <a-form-item label="订单编号">
            <a-input :value="currentAuditOrder.orderNo" disabled />
          </a-form-item>
          <a-form-item label="客户名称">
            <a-input :value="currentAuditOrder.customerName" disabled />
          </a-form-item>
          <a-form-item label="工程名称">
            <a-input :value="currentAuditOrder.projectName" disabled />
          </a-form-item>
          <a-form-item label="审核结果">
            <a-radio-group v-decorator="['auditResult', { rules: [{ required: true, message: '请选择审核结果' }] }]">
              <a-radio :value="1">通过</a-radio>
              <a-radio :value="9">驳回</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="审核意见" v-show="showRejectReason">
            <a-textarea
              v-decorator="[
                'rejectReason',
                {
                  rules: [
                    {
                      required: true,
                      message: '驳回订单必须填写驳回原因',
                      validator: (rule, value, callback) => {
                        const auditResult = this.auditForm.getFieldValue('auditResult')
                        if (auditResult === 9 && (!value || !value.trim())) {
                          callback('驳回订单必须填写驳回原因')
                        } else {
                          callback()
                        }
                      },
                    },
                  ],
                },
              ]"
              :rows="4"
              placeholder="请输入驳回原因（必填）"
            />
          </a-form-item>
          <a-form-item label="备注">
            <a-textarea v-decorator="['remark']" :rows="3" placeholder="请输入备注信息（选填）" />
          </a-form-item>
        </a-form>
      </a-spin>
    </a-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { getAction, deleteAction, putAction, postAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import ProductOrderModal from './modules/ProductOrderModal'
import { message } from 'ant-design-vue'
import JInput from '@/components/jeecg/JInput'
import JSelectEmployeeModal from '@/components/jeecgbiz/JSelectEmployeeModal'
import { getFileAccessHttpUrl } from '@/api/manage'
import CountTo from '@/components/count-to/CountTo'

export default {
  name: 'ProductOrderList',
  mixins: [JeecgListMixin],
  components: {
    ProductOrderModal,
    JInput,
    JSelectEmployeeModal,
    CountTo,
  },
  data() {
    return {
      description: '成品销售订单管理页面',
      // 当前登录用户的优化软件类型
      currentOptimizeSoftType: 0,
      // 当前登录用户的门窗生产类型
      currentWindowDoorType: 0,
      // 汇总数据时间范围
      summaryTimeRange: 'today',
      // 汇总数据
      summaryData: {
        totalOrders: 0,
        totalAmount: 0,
        totalCost: 0,
        totalProfit: 0,
        profitRate: 0,
      },
      // 查询条件
      queryParam: {
        orderNo: '',
        customerName: '',
        customerProvince: '',
        customerCity: '',
        customerDistrict: '',
        projectName: '',
        projectProvince: '',
        projectCity: '',
        projectDistrict: '',
        projectArea: '',
        status: '',
        orderDate: '',
        salesPersonId: '',
        deliveryDate: '',
        payStatus: '',
        minTotalAmount: undefined,
        maxTotalAmount: undefined,
        minTotalCost: undefined,
        maxTotalCost: undefined,
        minProfit: undefined,
        maxProfit: undefined,
        productSeries: '',
      },
      // 表格key，用于强制刷新
      tableKey: 0,
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '订单编号',
          align: 'center',
          dataIndex: 'orderNo',
          width: 120,
        },
        {
          title: '客户名称',
          align: 'center',
          dataIndex: 'customerName',
          width: 120,
        },
        {
          title: '客户地址',
          align: 'center',
          dataIndex: 'customerProvince',
          width: 180,
          scopedSlots: { customRender: 'customerAddressSlot' },
        },
        {
          title: '工程名称',
          align: 'center',
          dataIndex: 'projectName',
          width: 120,
        },
        {
          title: '工程地址',
          align: 'center',
          dataIndex: 'projectProvince',
          width: 180,
          scopedSlots: { customRender: 'projectAddressSlot' },
        },
        {
          title: '下单日期',
          align: 'center',
          dataIndex: 'orderDate',
          width: 100,
        },
        {
          title: '交付日期',
          align: 'center',
          dataIndex: 'deliveryDate',
          width: 100,
        },
        {
          title: '销售负责人',
          align: 'center',
          dataIndex: 'salesPersonName',
          width: 100,
        },
        {
          title: '销售额',
          align: 'center',
          dataIndex: 'totalAmount',
          width: 100,
          scopedSlots: { customRender: 'moneySlot' },
        },
        {
          title: '已付款',
          align: 'center',
          dataIndex: 'paidAmount',
          width: 100,
          scopedSlots: { customRender: 'moneySlot' },
        },
        {
          title: '未付款',
          align: 'center',
          dataIndex: 'unpaidAmount',
          width: 100,
          scopedSlots: { customRender: 'moneySlot' },
        },
        {
          title: '总成本',
          align: 'center',
          dataIndex: 'totalCost',
          width: 100,
          scopedSlots: { customRender: 'moneySlot' },
        },
        {
          title: '利润',
          align: 'center',
          dataIndex: 'profit',
          width: 100,
          scopedSlots: { customRender: 'moneySlot' },
        },
        {
          title: '订单状态',
          align: 'center',
          dataIndex: 'status',
          width: 100,
          scopedSlots: { customRender: 'statusSlot' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: 150,
          scopedSlots: { customRender: 'actionSlot' },
        },
      ],
      url: {
        list: '/oms/productSalesOrder/list',
        delete: '/oms/productSalesOrder/delete',
        deleteBatch: '/oms/productSalesOrder/deleteBatch',
        exportXlsUrl: '/oms/productSalesOrder/exportXls',
        getCurrentUserOptimizeSoftType: '/sys/employee/getCurrentUserOptimizeSoftType',
        updateCurrentUserOptimizeSoftType: '/sys/employee/updateCurrentUserOptimizeSoftType',
      },
      toggleSearchStatus: false,
      auditModalVisible: false,
      auditLoading: false,
      auditForm: this.$form.createForm(this),
      currentAuditOrder: {},
      showRejectReason: false,
    }
  },
  computed: {
    currentOptimizeSoftTypeText() {
      return this.currentOptimizeSoftType === 0 ? '长风优化软件' : '新格尔优化软件'
    },
    currentWindowDoorTypeText() {
      return this.currentWindowDoorType === 0 ? '窗户' : '门'
    },
  },
  created() {
    // 在created阶段获取优化软件类型和门窗类型
    this.getCurrentUserOptimizeSoftType()
    this.getCurrentUserWindowDoorType()

    // 页面加载时重置查询条件
    this.searchReset()
  },
  mounted() {
    // 组件挂载后，再次检查优化软件类型是否获取成功
    console.log('ProductOrderList组件已挂载，当前优化软件类型:', this.currentOptimizeSoftType)

    // 如果当前类型仍为默认值，重新获取一次
    if (this.currentOptimizeSoftType === 0) {
      console.log('尝试再次获取优化软件类型')
      this.getCurrentUserOptimizeSoftType()
    }
  },
  methods: {
    // 获取当前用户的优化软件类型
    getCurrentUserOptimizeSoftType() {
      console.log('正在获取当前用户的优化软件类型...')

      // 不再通过传递empId参数，直接从后端获取当前登录用户的优化软件类型
      getAction(this.url.getCurrentUserOptimizeSoftType)
        .then((res) => {
          if (res.success) {
            console.log('获取到用户优化软件类型:', res.result)
            this.currentOptimizeSoftType = res.result || 0 // 如果没有返回值，则默认为0

            // 获取完优化软件类型后，加载订单数据和汇总数据
            this.loadData(1)
            this.loadSummaryData()
          } else {
            console.error('获取优化软件类型失败:', res.message)
            message.warning('获取优化软件类型信息失败: ' + (res.message || '未知错误'))
            // 使用默认值并继续加载数据
            this.currentOptimizeSoftType = 0
            this.loadData(1)
            this.loadSummaryData()
          }
        })
        .catch((err) => {
          console.error('获取优化软件类型异常:', err)
          message.warning('获取优化软件类型信息异常，使用默认值')
          // 发生异常时使用默认值
          this.currentOptimizeSoftType = 0
          this.loadData(1)
          this.loadSummaryData()
        })
    },

    // 切换优化软件类型
    handleSwitchOptimizeSoftType() {
      // 切换为另一种类型
      const newType = this.currentOptimizeSoftType === 0 ? 1 : 0
      console.log('切换优化软件类型，当前:', this.currentOptimizeSoftType, '新类型:', newType)

      this.loading = true
      // 调用后端接口更新
      postAction(this.url.updateCurrentUserOptimizeSoftType, { optimizeSoftType: newType.toString() })
        .then((res) => {
          if (res.success) {
            this.currentOptimizeSoftType = newType
            message.success(`已切换为${this.currentOptimizeSoftTypeText}`)

            // 重新加载数据
            this.loadData(1)
          } else {
            console.error('切换优化软件类型失败:', res.message)
            message.error(res.message || '切换失败')
          }
        })
        .catch((err) => {
          console.error('切换优化软件类型异常:', err)
          message.error('系统异常，切换失败')
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 获取当前用户的门窗生产类型
    getCurrentUserWindowDoorType() {
      console.log('正在获取当前用户的门窗生产类型...')

      getAction('/sys/employee/getCurrentUserWindowDoorType')
        .then((res) => {
          if (res.success) {
            console.log('获取到用户门窗生产类型:', res.result)
            this.currentWindowDoorType = res.result || 0 // 如果没有返回值，则默认为0（窗户）
          } else {
            console.error('获取门窗生产类型失败:', res.message)
            message.warning('获取门窗生产类型信息失败: ' + (res.message || '未知错误'))
            // 使用默认值
            this.currentWindowDoorType = 0
          }
        })
        .catch((err) => {
          console.error('获取门窗生产类型异常:', err)
          message.warning('获取门窗生产类型信息异常，使用默认值')
          // 发生异常时使用默认值
          this.currentWindowDoorType = 0
        })
    },

    // 切换门窗生产类型
    handleSwitchWindowDoorType() {
      // 切换为另一种类型
      const newType = this.currentWindowDoorType === 0 ? 1 : 0
      console.log('切换门窗生产类型，当前:', this.currentWindowDoorType, '新类型:', newType)

      this.loading = true
      // 调用后端接口更新
      postAction('/sys/employee/updateCurrentUserWindowDoorType', { windowDoorType: newType.toString() })
        .then((res) => {
          if (res.success) {
            console.log('门窗生产类型切换成功')
            this.currentWindowDoorType = newType
            message.success('门窗生产类型切换成功')

            // 重新加载数据
            this.loadData(1)
          } else {
            console.error('切换门窗生产类型失败:', res.message)
            message.error(res.message || '切换失败')
          }
        })
        .catch((err) => {
          console.error('切换门窗生产类型异常:', err)
          message.error('系统异常，切换失败')
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 重写JeecgListMixin中的searchQuery方法，添加对汇总数据的更新
    searchQuery() {
      this.loadData(1)
      // 点击查询清空列表选中行
      this.selectedRowKeys = []
      this.selectionRows = []
    },

    // 重写JeecgListMixin中的searchReset方法，添加对汇总数据的更新
    searchReset() {
      this.queryParam = {
        orderNo: '',
        customerName: '',
        customerProvince: '',
        customerCity: '',
        customerDistrict: '',
        projectName: '',
        projectProvince: '',
        projectCity: '',
        projectDistrict: '',
        projectArea: '',
        status: '',
        orderDate: '',
        salesPersonId: '',
        deliveryDate: '',
        payStatus: '',
        minTotalAmount: undefined,
        maxTotalAmount: undefined,
        minTotalCost: undefined,
        maxTotalCost: undefined,
        minProfit: undefined,
        maxProfit: undefined,
        productSeries: '',
      }
      this.loadData(1)
    },

    // 查看订单详情
    handleDetail(record) {
      this.$refs.modalForm.show(record)
      this.$refs.modalForm.title = '详情'
      // 禁用提交按钮
      this.$refs.modalForm.disableSubmit = true
    },

    // 处理编辑，直接打开上传后的显示模块
    handleEdit(record) {
      // 打开编辑模式
      this.$refs.modalForm.edit(record)

      // 设置标题
      this.$refs.modalForm.title = '编辑'

      // 允许提交
      this.$refs.modalForm.disableSubmit = false

      // 直接跳转到订单信息标签页，跳过导入模块
      this.$nextTick(() => {
        // 设置标签页为订单信息(activeKey='1')
        if (this.$refs.modalForm) {
          this.$refs.modalForm.activeKey = '1'
        }
      })
    },

    // 处理新增
    handleAdd() {
      // 窗户类型或长风优化软件，使用现有订单创建逻辑
      this.$refs.modalForm.add()
      this.$refs.modalForm.form.setFieldsValue({
        status: 0, // 新增订单-待审核
      })
    },

    // 导出
    handleExport() {
      this.handleExportXls('成品销售订单')
    },
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
    // 表单提交后回调
    modalFormOk() {
      // 重新加载列表
      this.loadData()
      // 增加tableKey值强制表格重新渲染
      this.tableKey += 1
    },
    // 处理汇总数据时间范围变化
    handleSummaryTimeRangeChange() {
      // 仅更新汇总数据，不重新加载表格数据
      this.loadSummaryData()
    },

    // 加载汇总数据
    loadSummaryData() {
      const params = this.getQueryParams()

      // 根据选择的时间范围添加日期过滤条件
      const now = new Date()

      // 根据时间范围覆盖已有的beginDate参数
      if (this.summaryTimeRange === 'today') {
        // 直接获取当天日期的YYYY-MM-DD格式
        params.beginDate = now.toISOString().split('T')[0]
        params.endDate = params.beginDate
      } else if (this.summaryTimeRange === 'week') {
        const weekAgo = new Date(now)
        weekAgo.setDate(weekAgo.getDate() - 7)
        // 格式化日期为YYYY-MM-DD
        params.beginDate = weekAgo.toISOString().split('T')[0]
      } else if (this.summaryTimeRange === 'month') {
        const monthAgo = new Date(now)
        monthAgo.setMonth(monthAgo.getMonth() - 1)
        // 格式化日期为YYYY-MM-DD
        params.beginDate = monthAgo.toISOString().split('T')[0]
      }

      // 移除分页参数，因为汇总不需要分页
      delete params.pageNo
      delete params.pageSize

      // 确保所有的数值类型参数都被正确转换为数字，防止出现字符串类型导致的问题
      const numericFields = [
        'minTotalAmount',
        'maxTotalAmount',
        'minTotalCost',
        'maxTotalCost',
        'minProfit',
        'maxProfit',
      ]
      numericFields.forEach((field) => {
        if (params[field] !== undefined && params[field] !== null) {
          params[field] = Number(params[field])
        }
      })

      // 调用接口获取汇总数据
      getAction('/oms/productSalesOrder/summary', params).then((res) => {
        if (res.success) {
          this.summaryData = res.result || {
            totalOrders: 0,
            totalAmount: 0,
            totalCost: 0,
            totalProfit: 0,
            profitRate: 0,
          }

          // 计算利润率
          if (this.summaryData.totalAmount > 0) {
            this.summaryData.profitRate = ((this.summaryData.totalProfit / this.summaryData.totalAmount) * 100).toFixed(
              2
            )
          } else {
            this.summaryData.profitRate = 0
          }
        }
      })
    },
    // 重写加载数据方法
    loadData(arg) {
      if (arg === 1) {
        this.ipagination.current = 1
      }
      const params = this.getQueryParams()
      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            // 处理数据，设置默认值
            this.dataSource = (res.result.records || []).map((item) => {
              // 如果已付款为空，则设置为0
              if (item.paidAmount === null || item.paidAmount === undefined) {
                item.paidAmount = 0
              }

              // 如果未付款为空，则根据总额和已付款计算
              if (item.unpaidAmount === null || item.unpaidAmount === undefined) {
                item.unpaidAmount = item.totalAmount - item.paidAmount
              }

              // 确保payStatus有值
              if (item.payStatus === null || item.payStatus === undefined) {
                // 如果已付款等于总金额，则设置为已付清(2)
                if (item.paidAmount >= item.totalAmount) {
                  item.payStatus = 2
                }
                // 如果已付款大于0但小于总金额，则设置为部分付款(1)
                else if (item.paidAmount > 0) {
                  item.payStatus = 1
                }
                // 否则设置为未付款(0)
                else {
                  item.payStatus = 0
                }
              }

              return item
            })

            this.ipagination.total = res.result.total || 0
            // 增加tableKey值强制表格重新渲染
            this.tableKey += 1

            // 查询表格数据后同步更新汇总数据
            this.loadSummaryData()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 处理删除
    handleDelete(id) {
      this.$confirm({
        title: '确认删除',
        content: '删除订单将同时删除所有关联的明细、交易记录、进度记录和窗型数据，且无法恢复。是否确认删除？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          this.loading = true
          deleteAction(this.url.delete, { id: id })
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message || '删除成功')
                this.loadData()
                this.tableKey += 1 // 强制刷新表格
              } else {
                this.$message.error(res.message || '删除失败')
              }
            })
            .finally(() => {
              this.loading = false
            })
        },
      })
    },

    // 批量删除
    batchDel() {
      if (!this.selectedRowKeys || this.selectedRowKeys.length === 0) {
        this.$message.warning('请选择需要删除的记录!')
        return
      }

      const selectedCount = this.selectedRowKeys.length
      this.$confirm({
        title: '批量删除确认',
        content: `您选择了${selectedCount}条订单记录，删除这些订单将同时删除所有关联的明细、交易记录、进度记录和窗型数据，且无法恢复。是否确认删除？`,
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          this.loading = true
          deleteAction(this.url.deleteBatch, { ids: this.selectedRowKeys.join(',') })
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message || '批量删除成功')
                this.loadData()
                this.onClearSelected()
                this.tableKey += 1 // 强制刷新表格
              } else {
                this.$message.error(res.message || '批量删除失败')
              }
            })
            .finally(() => {
              this.loading = false
            })
        },
      })
    },

    // 查看订单进度
    handleViewProgress(record) {
      // 已移除进度查看功能
    },

    // 查看交易记录
    handleViewTransactions(record) {
      // 已移除交易记录查看功能
    },

    // 添加审核功能
    handleAudit(record) {
      this.currentAuditOrder = record
      this.auditModalVisible = true
      this.showRejectReason = false

      // 重置表单
      this.$nextTick(() => {
        this.auditForm.resetFields()

        // 设置默认值为通过
        this.auditForm.setFieldsValue({
          auditResult: 1,
        })

        // 监听审核结果变化
        const auditResultField = this.auditForm.getFieldInstance('auditResult')
        if (auditResultField && auditResultField.$on) {
          auditResultField.$on('change', (e) => {
            this.showRejectReason = e.target.value === 9
            // 如果切换到驳回，重置驳回原因字段的验证
            if (e.target.value === 9) {
              this.auditForm.validateFields(['rejectReason'], { force: true })
            }
          })
        }
      })
    },
    submitAudit() {
      this.auditLoading = true
      this.auditForm.validateFields((err, values) => {
        if (!err) {
          const auditResult = values.auditResult
          const rejectReason = values.rejectReason || ''
          const remark = values.remark || ''

          // 如果是驳回但没有填写驳回原因，显示错误信息
          if (auditResult === 9 && !rejectReason.trim()) {
            this.$message.error('驳回订单必须填写驳回原因')
            this.auditLoading = false
            return
          }

          const params = {
            id: this.currentAuditOrder.id,
            auditResult: auditResult,
            rejectReason: rejectReason,
            remark: remark,
          }

          postAction('/oms/productSalesOrder/audit', params)
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message || '审核成功')
                this.loadData()
                this.auditModalVisible = false
              } else {
                this.$message.error(res.message || '审核失败')
              }
            })
            .finally(() => {
              this.auditLoading = false
            })
        } else {
          this.auditLoading = false
        }
      })
    },
    cancelAudit() {
      this.auditModalVisible = false
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@/assets/less/TableExpand.less';

.ant-card-body .table-operator {
  margin-bottom: 18px;
}

.ant-table-tbody .ant-table-row td {
  padding-top: 15px;
  padding-bottom: 15px;
}

.anty-row-operator button {
  margin: 0 5px;
}

.ant-btn-danger {
  background-color: #ffffff;
}

.ant-modal-cust-warp {
  height: 100%;
}

.ant-modal-cust-warp .ant-modal-body {
  height: calc(100% - 110px) !important;
  overflow-y: auto;
}

.ant-modal-cust-warp .ant-modal-content {
  height: 90% !important;
  overflow-y: hidden;
}

/* 表格横向滚动样式 */
.ant-table-wrapper {
  overflow-x: auto;
}

.ant-table-body {
  overflow-x: auto !important;
}

/* 适配小屏幕设备 */
@media screen and (max-width: 1200px) {
  .ant-table-content {
    overflow-x: auto;
  }
}

/* 固定列样式 */
.ant-table-fixed-right {
  box-shadow: -6px 0 6px -4px rgba(0, 0, 0, 0.15);
}

.ant-table-tbody > tr > td.ant-table-fixed-columns-in-body {
  background-color: #fff;
}

/* 查询区域样式优化 */
.table-page-search-wrapper {
  margin-bottom: 18px;
  background-color: #fff;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.table-page-search-submitButtons {
  display: flex;
  align-items: center;
  margin-top: 24px;
}

/* 订单汇总卡片样式 */
.order-summary-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;

  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  }
}

.summary-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.summary-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;

  .anticon {
    margin-right: 8px;
    font-size: 20px;
  }
}

.summary-content {
  padding: 8px 0;
}

.summary-card {
  display: flex;
  align-items: center;
  padding: 16px;
  border-radius: 8px;
  color: #fff;
  height: 120px;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
  }

  &.summary-card-blue {
    background: linear-gradient(135deg, #1890ff, #096dd9);
  }

  &.summary-card-green {
    background: linear-gradient(135deg, #52c41a, #389e0d);
  }

  &.summary-card-orange {
    background: linear-gradient(135deg, #fa8c16, #d46b08);
  }

  &.summary-card-red {
    background: linear-gradient(135deg, #f5222d, #cf1322);
  }
}

.summary-icon {
  font-size: 36px;
  margin-right: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.2);
}

.summary-data {
  flex: 1;
}

.summary-label {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 8px;
}

.summary-value {
  font-size: 24px;
  font-weight: 600;
  display: flex;
  align-items: baseline;
  flex-wrap: wrap;
}

.summary-prefix {
  margin-right: 4px;
  font-size: 20px;
}

.summary-unit {
  margin-left: 4px;
  font-size: 16px;
  opacity: 0.8;
}

.profit-rate {
  font-size: 14px;
  opacity: 0.9;
  margin-top: 6px;
  width: 100%;
}
</style>
